package com.office.webSocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;


@ServerEndpoint("/webSocket")
@Component
public class WebSocket {

    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void opOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        System.out.println("websocket有新的连接总数：" + webSocketSet.size());
    }

    @OnClose
    public void onClose(Session session) {
        this.session = session;
        webSocketSet.remove(this);
        System.out.println("websocket连接断开总数：" + webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("websocket收到前端发来的消息：" + message);
    }

    /**
     * sendOfficeData
     * 发送WebSocket消息
     *
     * @param message /
     * @return void
     **/
    public void sendOfficeData(JSONObject message) {
        for (WebSocket webSocket : webSocketSet) {
            try {
                webSocket.session.getBasicRemote().sendText(message.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
